import React, { useState } from 'react';
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Space } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { MSGraphClientFactory } from '@microsoft/sp-http';

moment.locale('zh-cn');
const { Option } = Select;

const ProjectPlan = (props) => {
  console.log('Ceshi props:', props);
  const context = props?.context || props?.spContext;
  const [loading, setLoading] = useState(false);
  const [calendarLoading, setCalendarLoading] = useState(false);
  const [emailLoading, setEmailLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 生成随机数据
  const generateRandomData = () => {
    const projects = [
      '项目A开发计划',
      '项目B实施方案',
      '项目C进度报告',
      '项目D需求分析',
      '项目E测试计划'
    ];
    const statuses = ['进行中', '已完成', '待审核', '已暂停'];
    
    return Array.from({ length: 5 }, (_, index) => {
      // 生成未来1-30天的随机日期
      const randomDays = Math.floor(Math.random() * 30) + 1;
      const randomDate = moment().add(randomDays, 'days');
      const randomHour = Math.floor(Math.random() * 8) + 9; // 9:00 - 17:00
      const randomMinute = Math.floor(Math.random() * 4) * 15; // 0, 15, 30, 45
      
      randomDate.hour(randomHour).minute(randomMinute);
      
      return {
        key: String(index + 1),
        name: projects[index],
        status: statuses[Math.floor(Math.random() * statuses.length)],
        time: randomDate.format('M月D日 (周) HH:mm'),
        momentDate: randomDate // 保存 moment 对象以便后续使用
      };
    });
  };

  // 创建日历事件
  const createCalendarEvent = async (project) => {
    try {
      if (!context?.msGraphClientFactory) {
        console.error('msGraphClientFactory 未定义');
        return false;
      }

      const graphClient = await context.msGraphClientFactory.getClient();
      
      // 使用保存的 moment 对象
      const startDate = project.momentDate.toDate();
      const endDate = moment(project.momentDate).add(1, 'hours').toDate();

      const event = {
        subject: project.name,
        body: {
          contentType: "text",
          content: `项目状态：${project.status}\n项目详情：这是一个自动生成的项目计划。`
        },
        start: {
          dateTime: startDate.toISOString(),
          timeZone: "Asia/Shanghai"  // 使用中国时区
        },
        end: {
          dateTime: endDate.toISOString(),
          timeZone: "Asia/Shanghai"  // 使用中国时区
        }
      };

      await graphClient
        .api('/me/calendar/events')
        .post(event);

      return true;
    } catch (error) {
      console.error('创建日历事件失败:', error);
      return false;
    }
  };

  // 创建邮件
  const createEmail = async (project) => {
    try {
      if (!context?.msGraphClientFactory) {
        console.error('msGraphClientFactory 未定义');
        return false;
      }

      const graphClient = await context.msGraphClientFactory.getClient();
      
      const email = {
        message: {
          subject: `项目计划：${project.name}`,
          body: {
            contentType: "text",
            content: `项目状态：${project.status}\n项目时间：${project.time}\n\n这是一个自动生成的项目计划邮件。`
          },
          toRecipients: [
            {
              emailAddress: {
                address: "manager@yourcompany.com" // 替换为实际的收件人邮箱
              }
            }
          ]
        }
      };

      await graphClient
        .api('/me/sendMail')
        .post(email);

      return true;
    } catch (error) {
      console.error('创建邮件失败:', error);
      return false;
    }
  };

  // 生成随机数据
  const generateData = () => {
    if (!context) {
      message.error('无法获取SharePoint context，请确保已正确配置');
      return;
    }

    setLoading(true);
    try {
      // 生成随机数据
      const randomData = generateRandomData();
      setDataSource(randomData);
      message.success('数据生成成功！');
    } catch (error) {
      console.error('生成数据时出错:', error);
      message.error('生成数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 创建日历事件
  const handleCreateCalendar = async () => {
    if (!context) {
      message.error('无法获取SharePoint context，请确保已正确配置');
      return;
    }

    if (!context.msGraphClientFactory) {
      message.error('无法获取 Graph API 客户端，请确保已正确配置权限');
      return;
    }

    if (dataSource.length === 0) {
      message.warning('请先生成数据');
      return;
    }

    setCalendarLoading(true);
    try {
      let successCount = 0;
      for (const project of dataSource) {
        const success = await createCalendarEvent(project);
        if (success) successCount++;
      }
      
      if (successCount === dataSource.length) {
        message.success('所有日历事件创建成功！');
      } else {
        message.warning(`成功创建 ${successCount} 个日历事件，失败 ${dataSource.length - successCount} 个`);
      }
    } catch (error) {
      console.error('创建日历事件时出错:', error);
      message.error('创建日历事件失败，请稍后重试');
    } finally {
      setCalendarLoading(false);
    }
  };

  // 创建邮件
  const handleCreateEmail = async () => {
    if (!context) {
      message.error('无法获取SharePoint context，请确保已正确配置');
      return;
    }

    if (!context.msGraphClientFactory) {
      message.error('无法获取 Graph API 客户端，请确保已正确配置权限');
      return;
    }

    if (dataSource.length === 0) {
      message.warning('请先生成数据');
      return;
    }

    setEmailLoading(true);
    try {
      let successCount = 0;
      for (const project of dataSource) {
        const success = await createEmail(project);
        if (success) successCount++;
      }
      
      if (successCount === dataSource.length) {
        message.success('所有邮件发送成功！');
      } else {
        message.warning(`成功发送 ${successCount} 封邮件，失败 ${dataSource.length - successCount} 封`);
      }
    } catch (error) {
      console.error('发送邮件时出错:', error);
      message.error('发送邮件失败，请稍后重试');
    } finally {
      setEmailLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      width: 70,
    },
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 150,
    }
  ];

  // Handle table pagination, sorting, and filtering changes
  const handleTableChange = (pagination, filters, sorter) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
    // Note: Sorting and filtering logic can be added here if needed in the future
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '16px', fontWeight: 'normal' }}>项目计划</h2>
      
      <div style={{ marginBottom: '16px' }}>
        <Space>
          <Button 
            type="primary"
            onClick={generateData}
            loading={loading}
            disabled={!context}
          >
            生成随机数据
          </Button>
          <Button 
            type="primary"
            onClick={handleCreateCalendar}
            loading={calendarLoading}
            disabled={!context || dataSource.length === 0}
          >
            创建日历事件
          </Button>
          <Button 
            type="primary"
            onClick={handleCreateEmail}
            loading={emailLoading}
            disabled={!context || dataSource.length === 0}
          >
            发送邮件
          </Button>
        </Space>
        {!context && (
          <span style={{ marginLeft: '10px', color: '#ff4d4f' }}>
            无法获取 SharePoint context，请检查配置
          </span>
        )}
      </div>

      <div style={{ marginTop: '20px', marginBottom: '20px', borderBottom: '1px solid #f0f0f0' }}></div>

      <Table 
        columns={columns} 
        dataSource={dataSource.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
        loading={loading || calendarLoading || emailLoading}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: dataSource.length,
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomRight'],
        }}
        onChange={handleTableChange}
        bordered={false}
        rowClassName={(record, index) => index % 2 === 1 ? 'light-row' : ''}
      />

      <style jsx>{`
        .light-row {
          background-color: #eef4f8;
        }
        
        :global(.ant-table-thead > tr > th) {
          background-color: #f5f5f5;
          font-weight: normal;
        }
        
        :global(.ant-table-tbody > tr > td) {
          border-bottom: none;
        }
        
        :global(.ant-table-thead > tr > th) {
          border-bottom: none;
        }
        
        :global(.ant-table-container) {
          border-top: 1px solid #f0f0f0;
          border-left: 1px solid #f0f0f0;
          border-right: 1px solid #f0f0f0;
        }
        
        :global(.ant-table-thead > tr:first-child > th:first-child) {
          border-top-left-radius: 0;
        }
        
        :global(.ant-table-thead > tr:first-child > th:last-child) {
          border-top-right-radius: 0;
        }
      `}</style>
    </div>
  );
};

export default ProjectPlan;